package org.dru.clay.util.ui;

import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.io.Console;
import java.util.Arrays;

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class CredentialsDialog {

	public static void main(String[] args) {
		String[] strings = create("SSH authentication", "skldfjlksdfj", "Username", "Password");
		System.out.println(Arrays.toString(strings));
	}

	public static String[] create(String title, String description, String username, String password) {
		if (!GraphicsEnvironment.isHeadless()) {
			return swingCredentialsDialog(title, description, username, password);
		}

		final Console console = System.console();
		console.printf("#\n# %s\n# %s\n#\n", title, description);
		final String user = console.readLine("# %s: ", username);
		final char[] pass = console.readPassword("# %s: ", password);
		console.printf("#\n");

		return new String[] { user, new String(pass) };
	}

	private static String[] swingCredentialsDialog(String title, String description, String username, String password) {
		JPanel connectionPanel;

		JLabel userNameLabel = new JLabel(username + ":   ", JLabel.RIGHT);
		JTextField userNameField = new JTextField("");
		JLabel passwordLabel = new JLabel(password + ":   ", JLabel.RIGHT);
		JTextField passwordField = new JPasswordField("");
		connectionPanel = new JPanel(false);
		connectionPanel.setLayout(new BoxLayout(connectionPanel, BoxLayout.X_AXIS));
		JPanel namePanel = new JPanel(false);
		namePanel.setLayout(new GridLayout(0, 1));
		namePanel.add(userNameLabel);
		namePanel.add(passwordLabel);
		JPanel fieldPanel = new JPanel(false);
		fieldPanel.setLayout(new GridLayout(0, 1));
		fieldPanel.add(userNameField);
		fieldPanel.add(passwordField);
		connectionPanel.add(namePanel);
		connectionPanel.add(fieldPanel);

		if (JOptionPane.showOptionDialog(null, connectionPanel, "Clay - " + title, JOptionPane.OK_CANCEL_OPTION,
				JOptionPane.INFORMATION_MESSAGE, null, new String[] { "Ok", "Cancel" }, "hej") != 0) {
			return null;
		}
		return new String[] { userNameField.getText(), passwordField.getText() };
	}
}
